/*
 * Galaxium Messenger
 * 
 * Copyright (C) 2008 Ben Motmans <ben.motmans@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using Gtk;
using System;

using Galaxium.Gui;
using Galaxium.Core;

using Anculus.Gui;
using Anculus.Core;

namespace Galaxium.Gui.GtkGui
{
	public class ProgressMonitorDialog : Dialog, IProgressMonitor
	{
		public event EventHandler Cancelled;
		
		private VBox vbox;
		private ProgressBar progressbar;
		private Label labelStep;
		private Button buttonCancel;
		
		private bool _pulse = true;

		public ProgressMonitorDialog (string title, bool allowCancel)
			: base (title, null, DialogFlags.Modal)
		{
			vbox = new VBox (false, 6);
			
			progressbar = new ProgressBar ();
			labelStep = new Label ();
			labelStep.Xalign = 0f;
			
			buttonCancel = (Button)AddButton ("gtk-cancel", ResponseType.Cancel);
			buttonCancel.Clicked += CancelClicked;
			
			vbox.PackStart (progressbar, false, true, 0);
			vbox.PackStart (labelStep, false, true, 0);
			
			Add (vbox);
			ShowAll ();
		}
		
		public bool AllowCancel
		{
			get { return buttonCancel.Sensitive; }
			set { buttonCancel.Sensitive = value; }
		}
		
		public int StepCount
		{
			get
			{
				if (_pulse)
					return -1;
				
				return (int)progressbar.Adjustment.Upper;
			}
			set
			{
				_pulse = (value <= 0);
				
				if (!_pulse)
					progressbar.Adjustment.Upper = value;
			}
		}

		public void Initialize (string title, bool allowCancel)
		{
			this.Title = title;
			buttonCancel.Sensitive = allowCancel;
		}

		public void Step ()
		{
			Step (String.Empty);
		}

		public void Step (string description)
		{
			if (description == null)
				description = String.Empty;
			
			labelStep.Text = description;
			if (_pulse)
				progressbar.Pulse ();
			else
				progressbar.Adjustment.Value += 1;
		}

		public void Cancel ()
		{
			OnCancelled (EventArgs.Empty);
			Destroy ();
		}

		public void Finish ()
		{
			Destroy ();
		}
		
		protected virtual void CancelClicked (object sender, EventArgs e)
		{
			OnCancelled (EventArgs.Empty);
			Destroy ();
		}
		
		protected virtual void OnCancelled (EventArgs args)
		{
			if (Cancelled != null)
				Cancelled (this, args);
		}
	}
}
